package user

import (
	"github.com/labstack/echo/v4"
	"github.com/rs/zerolog/log"
	"techoiceness.com/aiagent/llm-gateway/internal/auth"
	"techoiceness.com/aiagent/llm-gateway/internal/server/response"
)

// Login 用户登录
func (h *UserHandler) Login(c echo.Context) error {
	var req LoginRequest
	if err := c.Bind(&req); err != nil {
		return response.BadRequest(c, "invalid request body")
	}

	// 验证请求参数
	if err := h.validator.Struct(&req); err != nil {
		return response.BadRequest(c, "validation failed: "+err.Error())
	}

	// 查找用户
	user, err := h.repos.GetUser().GetUserByUsername(c.Request().Context(), req.Username)
	if err != nil {
		log.Error().
			Str("username", req.Username).
			Msg("Failed to find user during login")
		return response.InternalServerError(c, "internal server error")
	}
	if user == nil {
		return response.Unauthorized(c, "invalid username or password")
	}

	// 验证密码
	if !auth.PasswordVerify(req.Password, user.PasswordHash) {
		return response.Unauthorized(c, "invalid username or password")
	}

	// 生成JWT token
	token, err := h.jwtManager.GenerateToken(user.ID, user.Username)
	if err != nil {
		log.Error().
			Str("user_id", user.ID.String()).
			Str("username", user.Username).
			Msg("Failed to generate JWT token for user login")
		return response.InternalServerError(c, "failed to generate token")
	}

	// 记录登录日志
	log.Info().
		Str("user_id", user.ID.String()).
		Str("username", user.Username).
		Msg("用户登录成功")

	// 返回响应
	responseData := LoginResponse{
		Token:    token,
		ID:       user.ID,
		Username: user.Username,
	}

	return response.Success(c, responseData)
}
